package cn.edu.pzhu.javaweb.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter({
        "/userinfo",
        "/change",
        "/destroy"
})
public class RootFilter extends HttpFilter implements Filter {

    private static final long serialVersionUID = 1L;

    public RootFilter() {
        super();
    }

    public void destroy() {}

    public void init(FilterConfig fConfig) throws ServletException {}

//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        if(request.getSession().getAttribute("username") == null){
//            response.sendRedirect("login.jsp");
//            return;
//        }
//        filterChain.doFilter(request, response);
//    }

        @Override
        protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {

        if(req.getSession().getAttribute("username")==null) {
            System.out.println("发现没有登录，请求被拦截……");
            res.sendRedirect("login.jsp");
            return;
        }
        super.doFilter(req, res, chain);
    }
}
